<template>
  <div class="login">
    <div class="main">
      <div class="formBox">
        <p>
          <label for="username">
            <span>账号：</span>
          </label>
          <input
            id="username"
            type="text"
            placeholder="请输入手机号"
            v-model="username"
            v-on:blur="blur()"
            @input="changInput(username)"
            @focus="focus"
          >
        </p>
        <ul class="formBoxUl" v-if="isformBoxUl">
          <li v-for="(item,i) in user_name_arr" :key="i" @click="formBoxItem(item)">{{item}}</li>
        </ul>
        <p>
          <label for="password">
            <span>密码：</span>
          </label>
          <input id="password" type="password" placeholder="请输入密码" v-model="password">
          <!-- <mt-field label="密码：" placeholder="请输入密码" type="password" v-model="password"></mt-field> -->
        </p>
        <span
          class="remember remember_y"
          :class="{'remember_n':!isremember}"
          @click="clickRemember"
        >
          <i class="iconfont icon-1"></i>
          记住密码
        </span>
        <div class="btn" @click="login">立即登录</div>
        <!-- <div class="btn" @click="login_2">立即登录</div> -->
        <div class="forget">
          <div class="itme" @click="isShowForget">忘记密码</div>
          <div class="itme" v-if="0">密保卡</div>
        </div>
      </div>
      <p class="bbh">版本V3.0.1.2</p>
    </div>
    <!-- 验证密保卡 -->
    <div id="EncryptedVerify" v-if="isEncryptedVerify">
      <div class="EncryptedVerify_main">
        <div class="title">
          <div class="iconfont icon-guanbi" @click="isEncryptedVerify=false"></div>密保卡验证
        </div>
        <div class="EncryptedVerify_content">
          <div class="verify_item">
            <div class="verify_box">{{code1}}</div>
            <div class="verify_box verify_boxInput">
              <input type="text" v-model="code1Val" maxlength="2">
            </div>
          </div>
          <div class="verify_item">
            <div class="verify_box">{{code2}}</div>
            <div class="verify_box verify_boxInput">
              <input type="text" v-model="code2Val" maxlength="2">
            </div>
          </div>
          <div class="verify_item">
            <div class="verify_box">{{code3}}</div>
            <div class="verify_box verify_boxInput">
              <input type="text" v-model="code3Val" maxlength="2">
            </div>
          </div>
        </div>
        <div class="sureBtn" @click="sureBtn">确定</div>
        <p class="cxp" @click="inquireMbk">查询密保卡</p>
      </div>
    </div>

    <!-- 密保卡短信mask -->
    <div class="encryptedInquire" v-if="isEncryptedInquire">
      <div class="main">
        <div class="title">
          <div class="iconfont icon-guanbi" @click="isEncryptedInquire=false"></div>密保卡查询
        </div>
        <p>密保卡查询需要短信验证，查询后 注意截图保存，每日查看3次。</p>
        <div class="inputBox">
          <label for="code">验证码</label>
          <input type="text" style="padding-left:3px;" v-model="YJELQss">
          <div class="btnBtn" v-if="isGetCodeBtn" @click="getCodeBtn">获取验证码</div>
          <div class="btnBtn1" v-else>获取验证码</div>
        </div>
        <div class="sureBtn" @click="codeSureBtn">确定</div>
      </div>
    </div>
    <div class="tishi" v-if="tsShow">
      <div class="main">
        <div class="txt">
          <span>恭喜您</span>
          <br>
          奖励 {{Gold}} 个章鱼丸
        </div>
      </div>
      <div class="btn" @click="inLogon()">进入章鱼世界</div>
    </div>

    <forget-pws v-if="forgetPage"/>
  </div>
</template>
<script>
import { Toast } from "mint-ui";
import {
  getToken,
  zylogin,
  getUserInfo,
  zylogin2,
  sendPassCardInfo,
  sendPassCardInfo1
} from "../../api.js";
import { getGuid, compileStr, uncompileStr } from "../../utils/index";
import { hex_md5 } from "../../utils/md5.js";
import qs from "qs";
import { mapGetters, mapActions } from "vuex";
import ForgetPws from "./ForgetPws";
import { im_ini } from "../../im";
import axios from "axios";
import $ from "jquery";
import { initParam } from "../../utils/argument";

export default {
  name: "login",
  data() {
    return {
      gid: "",
      uid: "",
      tsShow: false,
      isformBoxUl: false,
      isEncryptedInquire: false,
      isGetCodeBtn: true,
      YJELQss: "",
      username: "",
      password: "",
      isremember: true,
      isEncryptedVerify: false,
      codeArr: ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"],
      code1: "",
      code2: "",
      code3: "",
      code1Val: "",
      code2Val: "",
      code3Val: "",
      //mbUrl: "http://47.92.5.116:8078",
      mbUrl: "https://shield.912cc.com",
      isBuy: 2,
      user_id: "",
      auth: "",
      user_name_arr: [],
      Gold: ""
    };
  },
  computed: {
    ...mapGetters(["user", "forgetPage"])
  },
  components: { ForgetPws },
  mounted() {
    //注册后直接登录

    //记住账号
    if (localStorage.user_name_arr) {
      this.user_name_arr = JSON.parse(localStorage.user_name_arr);
    }
    this.get_token();
    //密保卡随机数
    this.showCode();

    this.isremember = localStorage.isremember == "false" ? false : true;
    if (this.isremember && localStorage.zyUserInfo) {
      let zyUserInfo = JSON.parse(localStorage.zyUserInfo);
      this.username = zyUserInfo.username;
      this.password = uncompileStr(zyUserInfo.password);
    }
  },
  methods: {
    direct() {
      console.log(this.$route.query.ID);
      if (!this.$route.query.ID) return;
      let obj = initParam(this.$route.query.ID.slice(3));
      let username = obj.split(",")[0];
      let encryptionPws = obj.split(",")[1];
      if (username) this.zyUserLogin(username, encryptionPws);
    },
    getCodeBtn() {
      this.getYzCode("1");
    },
    //查询密保卡按钮
    inquireMbk() {
      this.isGetCodeBtn = true;
      this.isEncryptedVerify = false;
      this.isEncryptedInquire = true;
    },
    codeSureBtn() {
      this.getYzCode("2");
    },
    //短信验证码
    getYzCode(MC) {
      sendPassCardInfo1({
        LoginMachine: getGuid(),
        ID: this.user_id,
        MC: MC,
        YJELQss: this.YJELQss,
        MS: this.MS
      }).then(res => {
        this.isGetCodeBtn = false;
        this.MS = res.data.Content;
        if (res.data.Success) {
          if (MC == 2) {
            this.isEncryptedInquire = false;
            this.$router.push("/encrypted");
          }
        } else {
          this.isEncryptedInquire = false;
          Toast({
            message: res.data.Content,
            duration: 2000
          });
        }
      });
    },
    blur() {
      this.isformBoxUl = false;
    },
    focus() {
      if (this.user_name_arr.length > 0) {
        this.isformBoxUl = true;
      }
    },
    formBoxItem(i) {
      this.username = i;
      this.password = "";
      this.isformBoxUl = false;
    },
    changInput(val) {
      if (val.length >= 11) this.isformBoxUl = false;
    },
    randomCode() {
      let num1 = Math.floor(Math.random() * 8 + 1).toString();
      let num2 = this.codeArr[Math.floor(Math.random() * 12 + 1) - 1];
      return num2 + num1;
    },
    showCode() {
      this.code1 = this.randomCode();
      this.code2 = this.randomCode();
      this.code3 = this.randomCode();
    },

    //获取验证密保卡的token (1)
    LoginGate() {
      let token = localStorage.zyToken.split(" ")[1];
      const username = this.username;
      const password = hex_md5(this.password);
      let url = `${
        this.mbUrl
      }/api/Original/LoginGate?Account=${username}&password=${password}&machine=${getGuid()}&token=${token}`;

      axios({
        method: "post",
        url: url,
        headers: {
          "Content-type": "application/x-www-form-urlencoded"
        }
      }).then(res => {
        if (res.data.Success) {
          this.auth = res.data.Token;
          localStorage.zyAuth = res.data.Token;
          // this.securityCard(res.data.Token);
          this.sendPassCard1();
        } else {
          //测试================================================== 2019-2-21
          this.sendPassCard1();
          Toast({
            message: "请检查账号和密码是否输入正确",
            duration: 2000
          });
        }
      });
    },
    //神父：是否启用密保卡
    securityCard() {
      let token = localStorage.zyAuth;
      let _this = this;
      let id = localStorage.zyUserId;
      const username = this.username;
      let url = `${
        this.mbUrl
      }/api/SecurityCard/SecurityCardEnable?userid=${id}`;

      $.ajax({
        type: "POST",
        url: url,
        headers: {
          "Content-type": "application/x-www-form-urlencoded",
          account: username,
          loginmachine: getGuid(),
          auth: token
        },
        success: function(result) {
          //没有启用 重新启用 生成
          if (!result.IsScuess) {
            _this.SecurityCardGenerate();
          }
          _this.sendPassCard2(); //MC==2 验证机器码是否一致
        }
      });
    },
    //SecurityCardGenerate 生成密保卡
    SecurityCardGenerate() {
      let _this = this;
      let userid = localStorage.zyUserId;
      const username = this.username;

      let url = `${
        this.mbUrl
      }/api/SecurityCard/SecurityCardGenerate?account=${username}&userid=${userid}`;
      $.ajax({
        type: "POST",
        url: url,
        headers: {
          "Content-type": "application/x-www-form-urlencoded",
          account: username,
          loginmachine: getGuid(),
          auth: this.auth
        },
        success: function(result) {
          // _this.$router.push("/encrypted");
        },
        error: function() {
          Toast({
            message: "生成失败",
            duration: 2000
          });
        }
      });
    },

    //验证密保卡
    sureBtn() {
      let _this = this;
      let url = `${this.mbUrl}/api/SecurityCard/SecurityCardVerify?account=${
        this.username
      }&userid=${this.user_id}&code1=${this.code1}&code2=${this.code2}&code3=${
        this.code3
      }&verifyCode=${this.code1Val}${this.code2Val}${this.code3Val}`;
      let token = localStorage.zyToken.split(" ")[1];
      let username = this.username;
      $.ajax({
        type: "POST",
        url: url,
        headers: {
          "Content-type": "application/x-www-form-urlencoded",
          account: username,
          loginmachine: getGuid(),
          auth: this.auth
        },
        success: function(result) {
          _this.isEncryptedVerify = false;
          if (result.StateCode == 0) {
            _this.zyUserLogin();
          } else {
            Toast({
              message: result.Message,
              duration: 2000
            });
          }
        }
      });
    },

    // verifyMibao() {},
    //验证机器码 MC==1 获取userid 验证是否购买密保卡(只能获取id 再杨鑫接口判断)  MC==2 验证机器码是否一致
    sendPassCard1() {
      sendPassCardInfo({
        ID: this.username,
        JYEPass: hex_md5(this.password),
        LoginMachine: getGuid(),
        MC: 1
      }).then(res => {
        this.user_id = res.data.Content.split("-")[1];
        localStorage.zyUserId = res.data.Content.split("-")[1];
        let ismai = res.data.Content.split("-")[0];
        console.log(res.data.Content.split("-")[0]);
        //==2没有购买  直接登录
        if (ismai == 2) {
          this.zyUserLogin();
          return;
        } else {
          //神父：是否启用密保卡
          this.securityCard();
        }
      });
    },
    //MC==2 验证机器码是否一致
    sendPassCard2() {
      sendPassCardInfo({
        ID: this.username,
        JYEPass: hex_md5(this.password),
        LoginMachine: getGuid(),
        MC: 2
      }).then(res => {
        if (res.data.Success) {
          this.zyUserLogin();
        } else {
          this.isEncryptedVerify = true;
        }
      });
    },

    //  登录前的token
    get_token() {
      getToken({
        username: "admin",
        password: "wdxlmjyw003",
        grant_type: "password"
      }).then(res => {
        if (res.data.access_token) {
          localStorage.zyToken = "bearer " + res.data.access_token;
          this.direct();
        } else {
          Toast({
            message: res.data.Content,
            duration: 2000
          });
        }
      });
    },
    login_2() {
      if (!this.username) {
        Toast({
          message: "用户名不正确",
          duration: 2000
        });
        return;
      }
      if (!this.password) {
        Toast({
          message: "密码不正确",
          duration: 2000
        });
        return;
      }
      this.rememberPsw();

      zylogin2({
        username: this.username,
        password: hex_md5(this.password),
        machine_id: getGuid(),
        version: "H3.0.0"
      }).then(res => {
        if (res.data.code == 200) {
          localStorage.zyPassword = hex_md5(this.password);
          console.log(hex_md5(this.password));
          let data = res.data;
          // console.log(data.data.yx_user.yx_token);
          localStorage.realToken = data.data.token;
          localStorage.zyLoginToken = data.data.operate_token;
          localStorage.zyUserId = data.data.UserID;
          localStorage.zyGameID = data.data.GameID;
          localStorage.yx_token = data.data.yx_user.yx_token;
          localStorage.yx_accid = data.data.yx_user.yx_accid;

          this.user_name_arr.push(this.username);
          this.user_name_arr = [...new Set(this.user_name_arr)];
          localStorage.user_name_arr = JSON.stringify(this.user_name_arr);
          localStorage.userInfo2 = JSON.stringify(data.data);
          localStorage.pay_password = "";

          this.$router.push("/");
          console.info(
            "-ttt7777777tt---",
            data.data.yx_user.yx_accid,
            data.data.yx_user.yx_token
          );
        }
      });
    },
    login() {
      if (!this.username) {
        Toast({
          message: "用户名不正确",
          duration: 2000
        });
        return;
      }
      if (!this.password) {
        Toast({
          message: "密码不正确",
          duration: 2000
        });
        return;
      }
      this.rememberPsw();
      // this.zyUserLogin();
      this.LoginGate();
      //手机唯一标识
    },
    zyUserLogin(name, pws) {
      zylogin({
        ID: name || this.username,
        JYEPass: pws || hex_md5(this.password),
        LoginMachine: getGuid(),
        MC: "0"
      })
        .then(res => {
          if (res.data.MessageID == 1) {
            localStorage.zyPassword = hex_md5(this.password);
            let data = res.data.EntityList[0];
            this.gid = data.GameID;
            this.uid = data.UserID;
            this.Gold = data.Gold;
            if (data.FristLogin == 1) {
              this.tsShow = true;
            } else {
              this.newToken();
            }
          } else if (res.data.MessageID == -1) {
            Toast({
              message: res.data.Content,
              duration: 2000
            });
          }
        })
        .catch(err => {});
    },
    inLogon() {
      this.newToken();
    },

    newToken(data) {
      getToken({
        username: this.gid,
        password: "520912yule",
        grant_type: "password"
      }).then(res => {
        // im_ini(data.GameID, hex_md5(this.password));
        this.user_name_arr.push(this.username);
        this.user_name_arr = [...new Set(this.user_name_arr)];
        localStorage.user_name_arr = JSON.stringify(this.user_name_arr);
        localStorage.zyLoginToken = "bearer " + res.data.access_token;
        localStorage.zyUserId = this.uid;
        localStorage.zyGameID = this.gid;
        this.$router.push("/");
      });
    },
    getUser(id) {
      getUserInfo({
        ID: id,
        LoginMachine: getGuid()
      }).then(res => {
        if (res.data && res.data.Success) {
          let data = res.data.EntityList[0];
          this.$store.dispatch("setUser", data);
        } else {
          Toast({
            message: "获取用户信息失败！",
            duration: 2000
          });
        }
      });
    },
    clickRemember() {
      this.isremember = !this.isremember;
      localStorage.isremember = this.isremember;
    },
    rememberPsw() {
      let zyUserInfo = {
        username: this.username,
        password: compileStr(this.password)
      };
      localStorage.zyUserInfo = JSON.stringify(zyUserInfo);
    },
    ...mapActions(["isShowForget"])
  }
};
</script>
<style lang="stylus" scoped>
.login {
  width: 7.5rem;
  height: 100%;
  min-height: 13.3rem;
  margin: 0 auto;
  background: #5A00FF url('../../assets/img/bj.jpg');
  background-size: 100% 100%;
  position: relative;

  .tishi {
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.9);
    position: fixed;
    left: 0;
    top: 0;
    z-index: 99;

    .main {
      width: 7.04rem;
      height: 6.94rem;
      background: #FFF url('../../assets/img/666.png');
      background-size: 100% 100%;
      border-radius: 0.2rem;
      position: absolute;
      left: 50%;
      top: 40%;
      transform: translate(-50%, -50%);

      .txt {
        color: #fff;
        width: 4.6rem;
        height: 2.1rem;
        text-align: center;
        margin: 3.9rem auto;
        line-height: 30px;
        font-size: 20px;
        padding-top: 0.3rem;

        span {
          line-height: 60px;
          font-size: 30px;
          line-height: 30px;
          font-size: 20px;
          font-family: 'HYk2gj';
        }
      }
    }

    .btn {
      width: 3.2rem;
      height: 0.92rem;
      line-height: 0.92rem;
      background: linear-gradient(-3deg, rgba(94, 143, 245, 1), rgba(152, 151, 253, 1));
      border-radius: 16px;
      position: absolute;
      left: 50%;
      top: 75%;
      transform: translate(-50%, -50%);
      color: #fff;
      text-align: center;
    }
  }

  .main {
    width: 6.82rem;
    background: #ffffff;
    box-shadow: 0px 7px 27px 0px rgba(0, 0, 0, 0.32);
    border-radius: 10px;
    position: absolute;
    top: 4.8rem;
    left: 50%;
    transform: translateX(-50%);

    .bbh {
      text-align: right;
      margin-bottom: 5px;
      font-size: 14px;
      margin-right: 10px;
    }

    .formBox {
      width: 6.22rem;
      position: relative;
      margin: 20px auto;

      p {
        border-bottom: 1px solid rgba(97, 97, 97, 0.5);
        margin-top: 30px;
        line-height: 1rem;
        font-size: 18px;

        input {
          margin-left: 15px;
        }
      }

      .formBoxUl {
        position: absolute;
        top: 0.9rem;
        left: 0.7rem;
        width: 5rem;
        height: 2.78;
        background: #FFF;
        border: 1px solid #AEAEAE;
        border-radius: 0.1rem;
        padding: 0.2rem 0.1rem;
        box-sizing: border-box;

        li {
          height: 0.7rem;
          line-height: 0.7rem;
          color: #606060;
          margin: 0 0.42rem;
          border-bottom: 1px solid rgba(165, 165, 165, 0.5);
        }
      }

      .remember {
        display: block;
        margin-top: 10px;
      }

      .remember_y {
        color: #1B9BFF;
      }

      .remember_n {
        color: #666;
      }

      .btn {
        width: 6.2rem;
        line-height: 1.05rem;
        background: rgba(0, 156, 255, 1);
        box-shadow: 0px 7px 27px 0px rgba(28, 0, 0, 0.32);
        border-radius: 10px;
        margin: 35px auto 10px auto;
        text-align: center;
        color: #fff;
        font-size: 24px;
      }

      .forget {
        width: 100%;
        line-height: 1.05rem;
        text-align: center;
        font-size: 18px;
        color: rgba(104, 104, 104, 1);
        display: flex;

        .itme {
          flex: 1;
        }
      }
    }
  }

  .encryptedInquire {
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.9);
    position: fixed;
    left: 0;
    top: 0;
    z-index: 99;

    .main {
      width: 7.04rem;
      height: 6.94rem;
      background: #FFF;
      border-radius: 0.2rem;
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      text-align: center;

      .title {
        .iconfont {
          position: absolute;
          left: 15px;
          font-size: 20px;
        }

        width: 6.63rem;
        height: 1rem;
        line-height: 1rem;
        font-size: 16px;
        border-bottom: 1px solid #898989;
        margin: 0 auto;
      }

      p {
        width: 80%;
        color: #898989;
        margin: 1rem auto;
        line-height: 20px;
      }

      .inputBox {
        display: flex;
        width: 90%;
        height: 0.6rem;
        line-height: 0.6rem;
        margin: 0 auto 0.8rem auto;
        font-size: 15px;
        text-align: center;

        input {
          width: 3rem;
          background: #D7D7D7;
          border-radius: 5px;
          margin: 0 5px;
        }

        .btnBtn {
          width: 2rem;
          background: #FF642C;
          color: #fff;
          border-radius: 0.06rem;
        }

        .btnBtn1 {
          width: 2rem;
          background: #666;
          color: #fff;
          border-radius: 0.06rem;
        }
      }

      .sureBtn {
        width: 6.18rem;
        height: 1rem;
        line-height: 1rem;
        background: linear-gradient(-42deg, rgba(249, 71, 1, 1), rgba(250, 81, 5, 1), rgba(253, 110, 17, 1));
        box-shadow: 0px 3px 9px 0px rgba(91, 24, 0, 0.47);
        border-radius: 0.1rem;
        color: #FFF;
        margin: 0.4rem auto;
        font-size: 20px;
      }

      .sureBtn1 {
        width: 6.18rem;
        height: 1rem;
        line-height: 1rem;
        background: #666;
        box-shadow: 0px 3px 9px 0px rgba(91, 24, 0, 0.47);
        border-radius: 0.1rem;
        color: #FFF;
        margin: 0.4rem auto;
        font-size: 20px;
      }
    }
  }
}

#EncryptedVerify {
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.9);
  position: fixed;
  left: 0;
  top: 0;
  z-index: 99;

  .EncryptedVerify_main {
    width: 7.04rem;
    // height: 7.94rem;
    background: #FFF;
    border-radius: 0.2rem;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    text-align: center;

    .title {
      .iconfont {
        position: absolute;
        left: 15px;
        font-size: 20px;
      }

      width: 6.63rem;
      height: 1rem;
      line-height: 1rem;
      font-size: 16px;
      border-bottom: 1px solid #898989;
      margin: 0 auto;
    }

    .EncryptedVerify_content {
      width: 85%;
      height: 2rem;
      margin: 1rem auto 1.2rem auto;
      display: flex;
      justify-content: space-around;

      .verify_item {
        width: 0.95rem;
        height: 2rem;
        display: flex;
        flex-direction: column;

        .verify_box {
          flex: 1;
        }

        .verify_boxInput {
          input {
            width: 100%;
            height: 100%;
            background: #D7D7D7;
            text-align: center;
          }
        }
      }
    }

    .sureBtn {
      width: 6.18rem;
      height: 1rem;
      line-height: 1rem;
      background: linear-gradient(-42deg, rgba(249, 71, 1, 1), rgba(250, 81, 5, 1), rgba(253, 110, 17, 1));
      box-shadow: 0px 3px 9px 0px rgba(91, 24, 0, 0.47);
      border-radius: 0.1rem;
      color: #FFF;
      margin: 0.4rem auto;
      font-size: 20px;
    }

    .cxp {
      text-align: center;
      margin: 0.6rem auto;
      color: rgba(253, 110, 17, 1);
    }
  }
}
</style>

